import axios from 'axios';
import {ElMessage} from 'element-plus';
import router from '../router/router.js';
import { useTokenStore } from "../token/token.js";

//  创建axios实例
const request = axios.create({
//     服务器基本路径
    baseURL: '/api',
//     超时
    timeout: 30000
})

//  请求拦截器
request.interceptors.request.use(
    config => {
        const tokenStore = useTokenStore();
        if(tokenStore.token) {
            config.headers.Authorization = tokenStore.token;
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);
//  响应拦截器
request.interceptors.response.use(
    response => {
        const res = response.data;
        if(res.code === 1) {
            return res;
        } else {
            return Promise.reject(res);
        }
    },
    error => {
        if(error.response && error.response.status === 401) {
            setTimeout(() => {
                ElMessage.error("请先登录")
                router.push('/')
            }, 1500)
        }
        return Promise.reject(error);
    }
)

export default request;